import { request, getPageQuery } from '@/utils'
import { history } from 'umi'
import { stringify } from 'querystring';
const GlobalModel = {
  namespace: 'global',
  state: {
    currentUser: {},
  },
  effects: {
    *fetchCurrent(_, { put }) {
      const res = yield request("user/info")
      if (res && res.code === 0) {
        yield put({ type: "saveCurrentUser", currentUser: res.data })
      } else {
        yield put({ type: "logout" })
      }
    },
    *logout(_, { put }) {
      localStorage.token = ""
      const { redirect } = getPageQuery();

      if (window.location.pathname !== '/login' && !redirect) {
        history.replace({
          pathname: '/login',
          search: stringify({
            redirect: window.location.href,
          }),
        });
      }
      yield put({ type: "saveCurrentUser", currentUser: {} })
    }
  },
  reducers: {
    saveCurrentUser(state: any, { currentUser }: any) {
      return { ...state, currentUser };
    }
  },
  subscriptions: {
  },
};
export default GlobalModel;
